package cn.kai.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.kai.enums.BizCodeEnum;
import cn.kai.exception.BizException;
import cn.kai.process.Process;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 公共工具类
 * Author: cKnight
 * Date: 2024/6/9
 */
@Slf4j
public class CommonUtils {


    /**
     * 校验必填项
     * @param args
     */
    public static void checkArgs(Object... args){
        for (Object item : args) {
            if (item instanceof String){
                if (StringUtils.isBlank((String) item)){
                    throw new BizException(BizCodeEnum.SYS_ARGS_ERROR);
                }
            }else if (item instanceof Collection){
                if (CollUtil.isEmpty((Collection<?>) item)) {
                    throw new BizException(BizCodeEnum.SYS_ARGS_ERROR);
                }
            }else if (Objects.isNull(item)){
                throw new BizException(BizCodeEnum.SYS_ARGS_ERROR);
            }
        }
    }



    /**
     * 响应json数据给前端
     *
     * @param response
     * @param obj
     */
    public static void sendJsonMessage(HttpServletResponse response, Object obj) {

        response.setContentType("application/json; charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.print(JSONObject.toJSONString(obj));
            response.flushBuffer();

        } catch (IOException e) {
            log.warn("响应json数据给前端异常:{}", e.toString());
        }
    }

    /**
     * 转换url
     *
     * @param url
     * @param params
     * @return
     */
    public static String transUrl(String url, Map<String, Object> params) {
        if (CollectionUtils.isEmpty(params)){
            return url;
        }
        String transParams = params.entrySet().stream()
                .map(obj -> obj.getKey() + "=" + obj.getValue().toString())
                .collect(Collectors.joining("&"));
        url = url + "?" + transParams;
        return url;
    }

    /**
     * 获取请求体参数
     * @param request
     * @return
     */
    public static String getRequestBodyParamsStr(HttpServletRequest request) {
        StringBuilder wholeStr = new StringBuilder();
        try (BufferedReader br = request.getReader()) {
            String str;
            while ((str = br.readLine()) != null) {
                wholeStr.append(str);
            }
        } catch (IOException e) {
            log.error("获取请求体参数异常:", e);
        }
        String result = wholeStr.toString().replaceAll(" ", "");
        log.info("获取请求体参数: {}", result);
        return result;
    }


    /**
     * 返回request
     * @return
     */
    public static RequestAttributes getRequest(){
        return RequestContextHolder.getRequestAttributes();
    }


    /**
     * 解析url路径参数
     * @param url
     * @return
     */
    public static JSONObject parsUrlPathParams(String url){
        if (!url.contains("?")){
            return null;
        }
        JSONObject jsonObject = new JSONObject();
        String params = StringUtils.split(url,"?")[1];
        String[] array = params.split("&");
        for (String obj : array) {
            if (!obj.contains("=")){
                continue;
            }
            String[] objSplit = obj.split("=");
            jsonObject.put(objSplit[0],objSplit[1]);
        }
        return jsonObject;
    }

    /**
     * 解析路径参数
     * @param url
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T parsUrlPathParams(String url,Class<T> clazz){
        JSONObject urlObject = parsUrlPathParams(url);
        if (Objects.nonNull(urlObject)){
            return urlObject.toJavaObject(clazz);
        }
        return ReflectUtil.newInstance(clazz);
    }




    public static String processBootContent(String content){
        content = content.replace("<p>", "　　");
        content = content.replace("</p>", "\n");
        content = content.replace("<div>", "");
        content = content.replace("</div>", "");
        content = content.replace("<br>", "\n");
        content = content.replace("</br>", "\n");
        content = content.replace("&nbsp;","　　");
        return content;
    }

    /**
     * 安全处理request
     * @param process
     */
    public static void safeRequestAttributes(Process process, RequestAttributes requestAttributess){
        try {
            RequestContextHolder.setRequestAttributes(requestAttributess);
            process.execute();
        }catch (Exception ignored){

        }finally {
            // 重置上下文信息
            RequestContextHolder.setRequestAttributes(null);
        }
    }

    public static <T> T safeRequestAttributes(Supplier<T> t, RequestAttributes requestAttributess){
        try {
            RequestContextHolder.setRequestAttributes(requestAttributess);
            return t.get();
        }finally {
            // 重置上下文信息
            RequestContextHolder.setRequestAttributes(null);
        }
    }

    /**
     * 分割数组
     * @param list 1-15,30-35
     * @return 1,2,3,4,5,6……15,30,31,32,33……35
     */
    public static List<Integer> splitNumRange(List<String> list){
        if (CollUtil.isNotEmpty(list)){
            List<Integer> result = new ArrayList<>();
            for (String string : list) {
                if (string.contains("-")){
                    String[] numRange = string.split("-");
                    int start = Integer.parseInt(numRange[0]);
                    int end = Integer.parseInt(numRange[1]);
                    for (int i = start; i <= end; i++) {
                        result.add(i);
                    }
                }
            }
            CollUtil.sort(result,Comparator.comparing(obj->obj));
            return result;
        }
        return new ArrayList<>();
    }

    /**
     * oss img 路经拼接  * @param path
     * @param bucketName
     * @param endpoint
     * @return
     */
    public static String ossImgJoin(String path, String bucketName, String endpoint) {
        return "https://".concat(bucketName)
                        .concat(".")
                        .concat(endpoint)
                        .concat("/")
                        .concat(path);
    }
}
